package com.example.nacosdemo.controller;

import com.example.nacosdemo.config.AppConfig;
import com.example.nacosdemo.config.ParamConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;

@RestController
@RefreshScope  // 开启配置自动刷新功能
public class ConfigController {

    // 注入配置类
    @Autowired
    private AppConfig appConfig;

    @Autowired
    private ParamConfig paramConfig;

    // 注入当前服务的端口号和服务名
    @Value("${server.port}")
    private String port;

    @Value("${spring.application.name}")
    private String serviceName;

    @Value("${spring.cloud.nacos.config.server-addr}")
    private String nacosServerAddr;

    /**
     * 获取所有配置信息
     */
    @GetMapping("/config")
    public Map<String, Object> getConfig() {
        Map<String, Object> configMap = new HashMap<>();
        configMap.put("serviceName", serviceName);
        configMap.put("port", port);
        configMap.put("message", appConfig.getMessage());
        configMap.put("version", appConfig.getVersion());
        configMap.put("debug", appConfig.isDebug());
        configMap.put("env", appConfig.getEnv());
        configMap.put("timeout", appConfig.getTimeout());
        configMap.put("nacosServerAddr", nacosServerAddr);
        configMap.put("appConfig", appConfig.toString());
        configMap.put("tKeyLabel", paramConfig.gettKeyLabel());
        return configMap;
    }

    /**
     * 获取特定的消息配置
     */
    @GetMapping("/config/message")
    public String getMessage() {
        return appConfig.getMessage();
    }

    /**
     * 获取版本信息
     */
    @GetMapping("/config/version")
    public String getVersion() {
        return appConfig.getVersion();
    }

    /**
     * 获取环境信息
     */
    @GetMapping("/config/env")
    public String getEnv() {
        return appConfig.getEnv();
    }

    /**
     * 获取调试模式状态
     */
    @GetMapping("/config/debug")
    public boolean isDebug() {
        return appConfig.isDebug();
    }
}